package xdu.lz.stage1_basic.chapter3_threadCommunicate;



import java.util.ArrayList;
import java.util.List;


/**
 * 线程数量的控制
 */
public class ThreadNumControl {
    private static final Object LOCK = new Object();
    private static final int MAX_COUNT = 3;
    private static int counter = 0;

    public static void main(String[] args) {

        List<Thread> wokerList = new ArrayList<>();
        Thread worker;
        for (int i = 0; i < 10; i++) {
            worker = createThread("M"+i);
            wokerList.add(worker);
            worker.start();
        }
        wokerList.stream().forEach(t-> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    private static Thread createThread(String name){
        return new Thread(()->{
            System.out.println(Thread.currentThread().getName()+" prepare to work");
            synchronized (LOCK){
                //如果达到了最大限制线程数，则等待
                while (counter >= MAX_COUNT){
                    try {
                        //被唤醒后就会同时去竞争LOCK，竞争到LOCK后会进入wait的代码，去执行wait后的代码
                        //然后只有退出while的条件
                        LOCK.wait();
                        System.out.println("***");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //增加当先工作的线程计数
                counter ++;
            }
            System.out.println(Thread.currentThread().getName()+" is working");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (LOCK){
                System.out.println(Thread.currentThread().getName()+" stop");
                //计数 --
                counter --;
                LOCK.notifyAll();
            }
        },name);
    }

}
